﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Data;
using System.Runtime;
using RAD.LightOne.Data;
using System.Runtime.CompilerServices;

namespace RAD.LightOne.Web.Security
{
    #region Documentation
    /// <summary>
    /// Classe de negócios para usuário, herda de <see cref="MembershipUser"/>.
    /// </summary>
    #endregion
    [Serializable]
    public class LightOneMembershipUser : MembershipUser
    {
        #region Fields

        private MembershipUserModel userData;
        
        #endregion

        #region Properties

        public string ApplicationName
        {
            get
            {
                return this.userData.Application;
            }
        }

        public override string Comment
        {
            get
            {
                return this.userData.Comment;
            }
            set
            {
                this.userData.Comment = value;
            }
        }

        public override DateTime CreationDate
        {
            get
            {
                return this.userData.CreationDate;
            }
        }

        public override string Email
        {
            get
            {
                return this.userData.Email;
            }
            set
            {
                this.userData.Email = value;
            }
        }

        public override bool IsApproved
        {
            get
            {
                return this.userData.IsApproved;
            }
            set
            {
                this.userData.IsApproved = value;
            }
        }

        public override bool IsLockedOut
        {
            get
            {
                return this.userData.IsLockedOut;
            }
        }

        public override bool IsOnline
        {
            get
            {
                return this.userData.IsOnline;
            }
        }

        public override DateTime LastActivityDate
        {
            get
            {
                return this.userData.LastActivityDate;
            }
            set
            {
                this.userData.LastActivityDate = value;
            }
        }

        public override DateTime LastLockoutDate { get { return this.userData.LastLockoutDate; } }

        public override DateTime LastLoginDate { 
            get { return this.userData.LastLoginDate.HasValue ?
                this.userData.LastLoginDate.Value : DateTime.MinValue; } 
            set { this.userData.LastLoginDate = value; } }

        public override DateTime LastPasswordChangedDate { get { return this.userData.LastPasswordChangedDate; } }

        public override string PasswordQuestion { get { return this.userData.PasswordQuestion; } }

        public override object ProviderUserKey { get {
#if DEBUG
            logger.Log("Property:{0}->{1}", "ProviderUserKey", this.userData.Id);
#endif

                                                         return this.userData.Id; 
        
        } }

        public override string UserName
        {
            get { return this.userData.UserName; }
        }
        
        public string Login
        {
            get { return this.userData.UserName; }
            set { this.userData.UserName = value; }
        }

        public override string ProviderName
        {
            get
            {
                return this.userData.ProviderName;
            }
        }

        #endregion

        #region Constructors

#if DEBUG
        Logger logger;
#endif
        /*private  LightOneMembershipUser():base ()
        {
            this.Initialize();
        }*/

        public LightOneMembershipUser(string providerName, string name, object providerUserKey, string email, string passwordQuestion, string comment, bool isApproved, bool isLockedOut, DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate, DateTime lastPasswordChangedDate, DateTime lastLockoutDate) :
            base(providerName, name, providerUserKey, email, passwordQuestion, comment, isApproved, isLockedOut, creationDate, lastLoginDate, lastActivityDate, lastPasswordChangedDate, lastLockoutDate)
        {
            this.Initialize();
        }

        internal LightOneMembershipUser(MembershipUserModel userData) 
        {
            if (userData == null) throw new ArgumentNullException("userData");
            this.Initialize();
            this.userData = userData;

        }

        #endregion

        #region Methods

        private void Initialize()
        {
#if DEBUG
            logger = new Logger(@"c:\temp\LightOneLog.txt");
#endif

            this.userData = new MembershipUserModel();
        }
        /* TODO: OVERRIDE
        public virtual string GetPassword();
        [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
        public virtual string ResetPassword();
        public virtual string ResetPassword(string passwordAnswer);
        
        */

        #region Documentation
        /// <summary>
        /// Return encrypted password.
        /// </summary>
        #endregion
        public override string GetPassword(string passwordAnswer)
        {
            using (DBEngine dbe = DBEngine.GetInstance())
            {
                return Convert.ToString(dbe.ExecuteScalar("select isNull(password,'') from users where passwordAnswer = {0} and Id={1}", passwordAnswer, this.userData));
            }
        }

        [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
        public override bool ChangePassword(string oldEncrypPassword, string newEncrypPassword)
        {
            using (DBEngine dbe = DBEngine.GetInstance())
            {
                return Convert.ToInt16(dbe.ExecuteNonQuery("update Users set password={0} where Id={1} and password={2}",newEncrypPassword, this.userData.Id,oldEncrypPassword)) > 0;
            }
        }

        public override bool UnlockUser()
        {
            this.userData.IsLockedOut = false;
            this.userData.Save();
            return true;
        }
        public void Save()
        {
            this.userData.Save();
        }

        public override int GetHashCode()
        {
            return this.userData.GetHashCode();
        }
        #endregion
    }
}
